package com.model.controller;

import com.model.ModelLoader;
import com.model.math.Point2D;
import com.model.math.Point3D;
import com.model.ModelBoundingBox;
import com.model.ModelBoundingBoxCalculator;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Map;
import java.util.List;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/api/model")
public class ModelController {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final String uploadDir = "uploads";
    
    public ModelController() {
        // 创建上传目录
        new File(uploadDir).mkdirs();
    }
    
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadModel(
            @RequestParam("file") MultipartFile file,
            @RequestParam("latitude") double latitude,
            @RequestParam("longitude") double longitude,
            @RequestParam("height") double height,
            @RequestParam("rotationX") double rotationX,
            @RequestParam("rotationY") double rotationY,
            @RequestParam("rotationZ") double rotationZ,
            @RequestParam("scale") double scale) {
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;
            
            // 保存文件
            Path filePath = Paths.get(uploadDir, filename);
            Files.write(filePath, file.getBytes());
            
            // 加载模型顶点
            Point3D[] modelVertices = ModelLoader.loadGLTFFile(filePath.toString());
            
            // 计算边缘线点
            List<Point2D> edgePoints = calculateBoundary(modelVertices, latitude, longitude, height, rotationX, rotationY, rotationZ, scale);
            
            // 生成GeoJSON
            String geoJson = ModelBoundingBoxCalculator.generateGeoJSON(edgePoints);
            
            // 创建响应
            ObjectNode response = objectMapper.createObjectNode();
            response.put("modelUrl", "/uploads/" + filename);
            response.set("boundary", objectMapper.readTree(geoJson));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            e.printStackTrace();
            ObjectNode errorResponse = objectMapper.createObjectNode();
            errorResponse.put("error", "上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    private List<Point2D> calculateBoundary(Point3D[] vertices, double latitude, double longitude, 
            double height, double rotationX, double rotationY, double rotationZ, double scale) {
        ModelBoundingBox transformer = new ModelBoundingBox(
            latitude, longitude, height, rotationX, rotationY, rotationZ, scale
        );
        
        return ModelBoundingBoxCalculator.calculateEdgePoints(vertices, transformer);
    }
} 